// import router from './router'
import router, {
  resetRouter
} from './router'
import store from './store/'
import indexApi from '@/api/index.js'
import { Message } from 'element-ui';
const defaultTitle = '管理系统'
import test1 from "@/views/test1"
import home from "@/views/layout/Main"
const whiteList = ['/login'];
// 全局前置守卫
router.beforeEach((to, from, next) => {

	document.title= to.meta.title ?to.meta.title +'-管理系统' : defaultTitle
	const token = sessionStorage.getItem("token");
	if(token){

			if(to.path == '/login'){
				Message({
				  message: '请先注销登录',
				  type: "error"
				});
				next('/home');
			}
			if(to.path == '/'){next('/home');}
			// 初始化菜单
			let menus = store.state.user.menus && store.state.user.menus.length > 0;
			// console.log(menus)	
			if(menus){
				// console.log(1)
				next();
			}else{
				// console.log(2)
				const roles = Math.random();
				store.dispatch('user/generateRoutes', roles).then((res) => {

					// console.log(res)
					// resetRouter();
					// 菜单显示
					router.options.routes = res
					// 添加菜单路由
					router.addRoutes(res)
					next({ ...to,
					  replace: true
					});
				});
			}


		
			// 获取用户信息
			// const userInfo = sessionStorage.getItem("userInfo");

			// if(!userInfo){
			// 	indexApi.getUser().then((res) => {
			// 		next();
			// 		sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
			// 	}).catch((error) => {
			// 		  //接口调用方法统一处理
			// 	});	
			// }else{
				// next();
			// }
			

	}else{
		if (whiteList.indexOf(to.path.toLowerCase()) !== -1) {
			
		  next();
		  // NProgress.done();
		} else {
			
		  next('/login');
		}
	}	



});

